package com.fyy.sentinel.config;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author fyy
 * @Description
 * @Date 2021/7/15 15:24
 */
//@Configuration
public class ZookeeperSentinelConfig {

    //连接zookeeper获取规则
    @PostConstruct
    void loadRules(){
        final String ZOOKEEPER_URL = "127.0.0.1:2181";
        final String ZOOKEEPER_FILE_PATH = "/sentinel/zookeeper";

        ReadableDataSource<String, List<FlowRule>> readableDataSource = new ZookeeperDataSource<>(
                ZOOKEEPER_URL, //zookeeper连接地址
                ZOOKEEPER_FILE_PATH,  //zookeeper文件路径
                source -> JSON.parseObject(source,new TypeReference<List<FlowRule>>(){}) //存放的数据类型
        );
        //注册数据资源到FlowRuleManager
        FlowRuleManager.register2Property(readableDataSource.getProperty());
    }

}
